package cn.piesat.translate.controller;

import cn.piesat.translate.common.Constants;
import cn.piesat.translate.service.ExcelOptionsService;
import cn.piesat.translate.utils.EasyExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author tw
 * @Description excel导入导出
 * @Date 2022/8/3 15:13
 **/
@Controller
@RequestMapping("/")
public class EasyExcelController {


    private static Logger log = LoggerFactory.getLogger(EasyExcelController.class);


    @Autowired
    private ExcelOptionsService excelOptionsService;

    /**
     * 测试视图解析器
     */
    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/merge")
    public String merge() {
        return "merge";
    }


    @RequestMapping("/upload")
    public void upload(MultipartFile file, HttpServletResponse response, String nameKey) {
        long l = System.currentTimeMillis();
        try {
            if (file.getOriginalFilename() != null) {
                List<List<String>> lists = excelOptionsService.readWithoutHead(file.getInputStream());
                if (lists.size() > 0) {
                    //统计词条，写入文件并导出下载
                    Map<String, Integer> map = excelOptionsService.dealData(lists, nameKey);
                    //开始写入文件
                    // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
                    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    response.setCharacterEncoding("utf-8");
                    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(file.getOriginalFilename().split("\\.")[0] + "_提取融合后", "UTF-8") + ".xlsx");
                    EasyExcelUtil.write(Constants.HEADER, map, response);
                }
            } else {
                response.sendRedirect("/errorPage?error=" + URLEncoder.encode("上传文件名为空！", "UTF-8"));
            }
            log.info("提取统计地名信息共耗时" + (System.currentTimeMillis() - l) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("读取融合文件异常" + e.getMessage());
            try {
                response.sendRedirect("/errorPage?error=" + URLEncoder.encode("读取融合文件异常！", "UTF-8"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    /**
     * 翻译数据融合
     *
     * @param request
     * @param response
     * @param nameKey
     */
    @RequestMapping("/upload/merge")
    public synchronized void fileMerge(HttpServletRequest request, HttpServletResponse response, String nameKey) {
        long l1 = System.currentTimeMillis();
        try {
            MultipartFile oriFile = ((MultipartHttpServletRequest) request).getFile("oriFile");
            MultipartFile tranFile = ((MultipartHttpServletRequest) request).getFile("tranFile");
            if (oriFile != null && tranFile != null) {
                List<List<String>> oriLists = excelOptionsService.readWithoutHead(oriFile.getInputStream());
                List<List<String>> tranLists = excelOptionsService.readWithoutHead(tranFile.getInputStream());
                if (oriLists.size() > 0) {
                    //开始比对原始文件并替换对应地名信息
                    log.info("原始文件" + (oriLists.size() - 1) + "条数据---翻译数据" + (tranLists.size() - 1) + "条数据");
                    long l = System.currentTimeMillis();
                    oriLists = excelOptionsService.exchangeName(oriLists, tranLists, nameKey);
                    log.info("地名翻译融合耗时" + (System.currentTimeMillis() - l) + "ms");
                    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    response.setCharacterEncoding("utf-8");
                    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(oriFile.getOriginalFilename().split("\\.")[0] + "_融合后", "UTF-8") + ".xlsx");
                    //获取第一行表头信息
                    List<String> list = oriLists.get(0);
                    EasyExcelUtil.write(list.toArray(new String[0]), oriLists, response);
                }
            } else {
                response.sendRedirect("/errorPage?error=" + URLEncoder.encode("上传文件名为空！", "UTF-8"));
            }
            log.info("融合提取总耗时" + (System.currentTimeMillis() - l1) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("读取融合文件异常" + e.getMessage());
            try {
                response.sendRedirect("/errorPage?error=" + URLEncoder.encode("读取融合文件异常！", "UTF-8"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @RequestMapping("/errorPage")
    public String error(@RequestParam("error") String error, Model model) {
        model.addAttribute("msg", error);
        return "error";
    }

}
